<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>WebSocket 客户端测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        #messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin: 10px 0;
            background-color: #f9f9f9;
            border-radius: 5px;
            font-size: 14px;
            line-height: 1.5;
        }
        .message {
            margin: 5px 0;
            padding: 5px;
            border-left: 3px solid #007bff;
            background-color: #e9f7fe;
        }
        .system {
            color: #28a745;
            font-style: italic;
        }
        .self {
            color: #007bff;
            text-align: right;
        }
        .others {
            color: #dc3545;
        }
        input[type="text"] {
            width: 70%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }
        button {
            padding: 10px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #0056b3;
        }
        #status {
            margin-top: 10px;
            font-weight: bold;
            color: #d9534f;
        }
        .connected {
            color: #5cb85c;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>💬 WebSocket 客户端</h1>
    <p>连接地址: <code>ws://localhost:8080/ws</code></p>

    <button id="connectBtn">连接</button>
    <button id="disconnectBtn" disabled>断开</button>
    <span id="status">未连接</span>

    <div id="messages"></div>

    <div>
        <input type="text" id="messageInput" placeholder="输入消息..." disabled />
        <button id="sendBtn" disabled>发送</button>
    </div>
</div>

<script>
    let socket = null;
    const messages = document.getElementById('messages');
    const messageInput = document.getElementById('messageInput');
    const sendBtn = document.getElementById('sendBtn');
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    const status = document.getElementById('status');

    // 添加消息到聊天框
    function addMessage(text, className = '') {
        const div = document.createElement('div');
        div.className = `message ${className}`;
        div.innerHTML = `<strong>${new Date().toLocaleTimeString()}</strong>: ${text}`;
        messages.appendChild(div);
        messages.scrollTop = messages.scrollHeight; // 滚动到底部
    }

    // 连接 WebSocket
    function connect() {
        // 使用原生 WebSocket（若未启用 SockJS）
        socket = new WebSocket("ws://localhost:8080/ws");

        socket.onopen = () => {
            console.log("WebSocket 已连接");
            status.textContent = "已连接";
            status.className = "connected";
            messageInput.disabled = false;
            sendBtn.disabled = false;
            connectBtn.disabled = true;
            disconnectBtn.disabled = false;
            addMessage("✅ 你已连接到服务器。", "system");
        };

        socket.onmessage = (event) => {
            console.log("收到消息:", event.data);
            addMessage(event.data, "others");
        };

        socket.onclose = (event) => {
            console.log("连接关闭:", event);
            status.textContent = "已断开";
            status.className = "";
            messageInput.disabled = true;
            sendBtn.disabled = true;
            connectBtn.disabled = false;
            disconnectBtn.disabled = true;
            addMessage(`❌ 连接已关闭: ${event.reason || '未知原因'}`, "system");
        };

        socket.onerror = (error) => {
            console.error("WebSocket 错误:", error);
            addMessage("❌ 发生错误，请查看控制台。", "system");
        };
    }

    // 发送消息
    function sendMessage() {
        const value = messageInput.value.trim();
        if (!value || !socket || socket.readyState !== WebSocket.OPEN) return;

        socket.send(value);
        addMessage(`你说: ${value}`, "self");
        messageInput.value = '';
    }

    // 断开连接
    function disconnect() {
        if (socket) {
            socket.close(1000, "用户主动断开");
        }
    }

    // 绑定按钮事件
    connectBtn.addEventListener('click', connect);
    disconnectBtn.addEventListener('click', disconnect);
    sendBtn.addEventListener('click', sendMessage);

    // 回车发送
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
</script>
</body>
</html>